package com.sy.core.web;

import com.alibaba.fastjson.JSONObject;
import com.sy.core.model.SysMenu;
import com.sy.core.model.SysUser;
import com.sy.core.model.common.MenuTree;
import com.sy.core.model.common.Permissions;
import com.sy.core.util.BaseUUID;
import com.sy.core.util.MD5Util;
import com.sy.core.util.RestResult;
import com.sy.core.util.SysConst;
import netscape.javascript.JSObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("login")
public class LoginCtl extends BaseCtl{
    @Resource
    private RedisTemplate<Object,Object> template;
    @RequestMapping("login_in")
    public RestResult loginIn(SysUser sysUser){
        RestResult rr = null;
        try {
            String password=sysUser.getPassword();
            String mobile=sysUser.getPhone();
            if(sysUser.getPhone().equals("")||sysUser.getPhone().equals("")){
                rr = new RestResult("201","用户名密码不能为空");
            }else{
                //1.构造登录令牌 UsernamePasswordToken
                //加密密码
                password = new Md5Hash(password,mobile,3).toString(); //1.密码，盐，加密次数
                UsernamePasswordToken upToken = new UsernamePasswordToken(mobile,password);
                //2.获取subject
                Subject subject = SecurityUtils.getSubject();
                //3.调用login方法，进入realm完成认证
                subject.login(upToken);
                //4.获取sessionId
                String sessionId = (String)subject.getSession().getId();
                System.err.println(sessionId);
                //5.构造返回结果
                //6.subject获取所有的安全数据集合
                PrincipalCollection principals = subject.getPrincipals();
                Permissions permissions = new Permissions();
                if(principals!=null&&!principals.isEmpty()){
                    permissions = (Permissions) principals.getPrimaryPrincipal();
                }
                permissions.setToken(sessionId);
                rr = new RestResult("200","登录成功",permissions);
               /* if(!sysUser.getPhone().matches(SysConst.PHONE)) {//检查用户名是手机号还是账号
                    sysUser.setAccount(sysUser.getPhone());
                    sysUser.setPhone(null);
                }
                sysUser.setPassword(null);
                List<SysUser> sysUserList = sysUserService.queryByCondition(sysUser);//通过用户名查询用户信息
                if(sysUserList!=null&&sysUserList.size()>0){
                    if(MD5Util.generate(password,sysUserList.get(0).getSalt()).equals(sysUserList.get(0).getPassword())){
                        Map<String,Object> map = new HashMap<>();
                        String token = "MMS"+ BaseUUID.getUUID();
                        List<MenuTree> menus = getAuthorization(sysUserList.get(0).getRolePk(),"1");//功能类型1菜单2.按钮3.API
                        List<MenuTree> points= getAuthorization(sysUserList.get(0).getRolePk(),"2");
                        List<MenuTree> apis= getAuthorization(sysUserList.get(0).getRolePk(),"3");
                        map.put("MENU_LIST", JSONObject.toJSONString(points));
                        map.put("POINT_LIST", JSONObject.toJSONString(menus));
                        map.put("APIS_LIST", JSONObject.toJSONString(apis));
                        map.put("token",token);
                        map.put("user", JSONObject.toJSONString(sysUserList.get(0)));
                        template.opsForValue().set(token,sysUserList.get(0),24*60*60*1000, TimeUnit.MILLISECONDS);
                        rr = new RestResult("200","登录成功",map);
                    }else{
                        rr = new RestResult("201","用户名或密码不正确");
                    }
                }else{
                    rr = new RestResult("201","用户名或密码不正确");
                }*/
            }
        } catch (AuthenticationException e) {
            rr= new RestResult("201","用户名或密码不匹配");
            //throw new ArithmeticException();
        }
        return rr;
    }

    @RequestMapping("/logout")
    public RestResult logout(HttpServletResponse response) {
        Subject lvSubject=SecurityUtils.getSubject();
        lvSubject.logout();
        return new RestResult("401","请登录");
    }

    public static void main(String[] args) {
        String password = new Md5Hash("111111","13761086769",3).toString();
        System.out.println(password);
    }

}
